﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Xiaov.SmartWeb.Infrastructure.ExtMethod;
using Xiaov.SmartWeb.Model.ActiveRecord;

namespace Xiaov.SmartWeb.Application
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
            if (!this.IsPostBack)
            {
                this.ViewState["GUID"] = System.Guid.NewGuid().ToString();
                this.h_guid.Value = this.ViewState["GUID"].ToString();
            }
        }
        protected static void SignIn(S_PM_USER pUser)
        {
            System.Web.Security.FormsAuthenticationTicket tk = new System.Web.Security.FormsAuthenticationTicket(1, pUser.USERID.ToString(), DateTime.Now, DateTime.Now.AddMonths(1), true, "", System.Web.Security.FormsAuthentication.FormsCookiePath);
            string key = System.Web.Security.FormsAuthentication.Encrypt(tk);
            HttpCookie ck = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, key);
            ck.Domain = System.Web.Security.FormsAuthentication.CookieDomain;  
            HttpContext.Current.Response.Cookies.Add(ck);
        }

        private string GetReturnUrl()
        {
            string reUrl = "Default.aspx";
            object defaulturl = Request.Params["ReturnUrl"];
            if (defaulturl != null)
            {
                if (!String.IsNullOrEmpty(defaulturl.ToString()))
                {
                    reUrl = defaulturl.ToString();
                }
            }
            return reUrl;

        }

        protected void BtnLogin_Click(object sender, EventArgs e)
        {

            IList<S_PM_USER> PUser = S_PM_USER.FindAllByProperty("LOGINNAME", tb_user.Text).ToList();
            if (PUser.Count>0)
            {
                if (PUser.First().PASSWORD == tb_pwd.Text.Encrypt())
                {
                    #region 检查验证码
                    if ((Session["CheckCode"] != null) && (Session["CheckCode"].ToString() != ""))
                    {
                        if (Session["CheckCode"].ToString().ToLower() != this.tb_code.Text.ToLower())
                        {
                            Session["CheckCode"] = null;
                            Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("提示", "验证码错误！", "Login.aspx");
                        }
                        else
                        {
                            Session["CheckCode"] = null;
                        }
                    }                    
                    #endregion
                    SignIn(PUser.First());
                    Response.Redirect(GetReturnUrl(), true);
                }
            }
            Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("提示", "用户名或密码错误！", "Login.aspx");

        }
    }
}